const db = require('../modules/db')
const moment = require('moment')

//话题


//查询所有并且分页
exports.list = async (req, res, next) => {
// 获取路由中的参数对象

  let {_page = 1 , _limit = 20} = req.query

  if (_page < 1) {
    _page = 1
  }
  if (_limit < 1) {
    _page = 1
  }
  if (_limit > 20) {
    _page = 20
  }
  const start = (_page - 1) * _limit
  try {
  const sqlStr = `
    SELECT * FROM topics order by id desc LIMIT ${start}, ${_limit} 
  `
  const list = await db.query(sqlStr)
  //总页数
  const [count] = await db.query(`SELECT count(*) as count FROM topics `)
  res.status(200).json({list,count})
  } catch {
    next(err)
  }
}


exports.once = async (req, res, next) => {
  try {
    const {id} = req.params
    const strSql = ` SELECT * FROM topics WHERE id = ${id} `
    const [ret] = await db.query(strSql)
    res.status(200).json(ret)
  } catch(err) {
    next(err);
  }

}


exports.create = async (req, res, next) => {
  const body = req.body
        body.id = req.session.user.id
        body.create_time = moment().format('YYYY-MM-DD hh:mm:ss')
        body.modify_time = moment().format('YYYY-MM-DD hh:mm:ss')

  const sqlStr = `INSERT INTO topics(title, content, user_id, create_time, modify_time)
    VALUES(
    '${body.title}',
    '${body.content}',
    '${body.id}',
    '${body.create_time}',
    '${body.modify_time}'
    ) `

  try {
    const topci = await db.query(sqlStr)
    const topciData =  await db.query(`SELECT * FROM topics WHERE id = ${topci.insertId}`)
    res.status(200).json(topciData)
    } catch {
    res.status(400).json({
      error: '错误：数据库获取数据失败'
    })
    } 

}

exports.update = async (req, res, next) => {
  try {
    const {id} = req.params
    const {title, content} = req.body
    const sqlStr = `UPDATE topics SET title='${title}', content='${content}', modify_time = '${moment().format('YYYY-MM-DD hh:mm:ss')}'
     WHERE id=${id} `
    await db.query(sqlStr)
    const [topci] = await db.query(`SELECT * FROM topics WHERE id = ${id}`)
    res.status(200).json(topci)
  } catch (err) {
    next(err)
  }
}

exports.delete = async (req, res, next) => {

  try {
    const {id} = req.params
    const sqlStr = `DELETE FROM topics WHERE id = ${id}`
    await db.query(sqlStr)
    res.status(201).json({})
  } catch (err) {
    next (err)
  }
}
